// index.js
import { createScopedThreejs } from '../../threejs/threejs-miniprogram';
import { registerGLTFLoader } from '../../threejs/gltf-loader';

var camera, scene, renderer, model, camera_parent;
var requestAnimationFrame;

const app = getApp()
Page({
  data: {
    level: 1
  },

  /**
   * 垃圾分类
   */
  getLitterType() {
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url:  app.globalData.url + '/garbage_classification/',
          filePath: tempFilePaths[0],
          name: 'file',
          success(res) {
            console.log(res)
            var json = JSON.parse(res.data)

            wx.showModal({
              title: '识别成功',
              content: '该垃圾为：' + json.result,
              showCancel: false
            })
          },
          fail() {
            wx.showModal({
              title: '识别失败',
              content: '原因：连接失败',
              showCancel: false
            })
          }
        })
      }
    })
  },

  /**
   * 跳转获取碳币
   */
  goToCarbon() {
    wx.navigateTo({
      url: '../coin/coins/index'
    })
  },

  onLoad() {
    let that = this;
    wx.request({
      url: 'http://127.0.0.1:8000/credit_house/',
      method: "GET",
      headers: {
        'Content-Type': 'application/json'
      },
      data: {
        user_id: getApp().globalData.user.userId
      },
      success: function (res) {
        console.log(res.data)

        if (res.statusCode == 500) {
          wx.showToast({
            title: '获取失败',
            icon: 'error',
            duration: 2000
          })
        } else {
          that.setData({
            level: res.data.level
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '连接失败',
          icon: 'error',
          duration: 2000
        })
      }
    })

    var query = wx.createSelectorQuery();
    query.select('#webgl').node().exec((res) => {

      var canvas = res[0].node;
      // 设置背景透明
      var gl = canvas.getContext('webgl', {
        alpha: true
      });

      if (canvas != undefined) {
        //  canvas.width 和canvas.style都需要设置，否则无法显示渲染
        canvas.width = canvas._width;
        canvas.height = canvas._height;
        requestAnimationFrame = canvas.requestAnimationFrame;
        that.init(canvas);
      }
    });
  },

  init: function (canvas) {
    let that = this;
    const THREE = createScopedThreejs(canvas)
    registerGLTFLoader(THREE)

    if (this.data.level == 3) {
      //设置相机
      camera = new THREE.PerspectiveCamera(45, canvas.width / canvas.height, 1, 100);
      camera.position.set(10, 10, 10)
      camera.lookAt(new THREE.Vector3(0, 0, 0))
      scene = new THREE.Scene()

      //将相机放一个三维物体里
      camera_parent = new THREE.Object3D();
      camera_parent.position.set(0, 0, 0);
      camera_parent.add(camera);

      //设置光线
      var light = new THREE.HemisphereLight(0xffffff, 0xffffff)
      light.position.set(10, 10, 10)
      camera_parent.add(light);
      // scene.add(light)
      light = new THREE.DirectionalLight(0xffffff)
      light.position.set(10, 10, 10)
      // scene.add(light)
      camera_parent.add(light);

      scene.add(camera_parent);


      //加载外部模型
      var loader = new THREE.GLTFLoader()
      loader.load(wx.env.USER_DATA_PATH + '/1/scene.gltf', function (gltf) {
        model = gltf.scene
        scene.add(model)
      }, undefined, function (e) {
        console.error(e)
      });
    } else if (this.data.level == 1) {
      //设置相机
      camera = new THREE.PerspectiveCamera(38, canvas.width / canvas.height, 1, 100);
      camera.position.set(17, 17, 17);
      camera.lookAt(new THREE.Vector3(0, 0, 0));
      scene = new THREE.Scene();

      //将相机放一个三维物体里
      camera_parent = new THREE.Object3D();
      camera_parent.position.set(0, 0, 0);
      camera_parent.add(camera);
      scene.add(camera_parent);

      //设置光线
      var light = new THREE.HemisphereLight(0xffffff, 0x444444)
      light.position.set(0, 20, 0)
      scene.add(light)
      light = new THREE.DirectionalLight(0xffffff)
      light.position.set(0, 20, 10)
      scene.add(light)
      //加载外部模型
      var loader = new THREE.GLTFLoader()
      loader.load(wx.env.USER_DATA_PATH + '/6/scene.gltf', function (gltf) {
        model = gltf.scene
        scene.add(model)
      }, undefined, function (e) {
        console.error(e)
      });
    } else {
      //设置相机
      camera = new THREE.PerspectiveCamera(100, canvas.width / canvas.height, 0.25, 100);
      camera.position.set(100, 100, 100);
      camera.lookAt(new THREE.Vector3(0, 0, 0));
      scene = new THREE.Scene();

      //将相机放一个三维物体里
      camera_parent = new THREE.Object3D();
      camera_parent.position.set(0, 0, 0);
      camera_parent.add(camera);
      scene.add(camera_parent);

      //设置光线
      var light = new THREE.HemisphereLight(0xffffff, 0x444444)
      light.position.set(0, 20, 0)
      scene.add(light)
      light = new THREE.DirectionalLight(0xffffff)
      light.position.set(0, 20, 10)
      scene.add(light)
      //加载外部模型
      var loader = new THREE.GLTFLoader()
      loader.load(wx.env.USER_DATA_PATH + '/4/scene.gltf', function (gltf) {
        model = gltf.scene
        scene.add(model)
      }, undefined, function (e) {
        console.error(e)
      });
    }

    renderer = new THREE.WebGLRenderer({ antialias: true })
    renderer.setSize(canvas.width, canvas.height)
    //调用动画
    that.animate(model)
  },

  animate: function () {
    let that = this

    requestAnimationFrame(that.animate)
    renderer.render(scene, camera)
  },

  roll: function (e) {
    console.log('roll')
    let that = this
    camera_parent.rotateY((2 / 180) * Math.PI); //向上旋转

    let timerAnimate = setTimeout(function () {
      that.roll(e)
    }, 100)

    if (that.data.stopRolling) {
      clearTimeout(timerAnimate)
    }
  },

  rollStart() {

    this.setData({
      stopRolling: false
    })
  },

  rollEnd() {

    this.setData({
      stopRolling: true
    })
  }
})
